package com.rongshu.sendmessage.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.rongshu.sendmessage.R;
import com.rongshu.sendmessage.activity.MessageDetailActivity;
import com.rongshu.sendmessage.activity.MoreMessageActivity;
import com.rongshu.sendmessage.activity.SearchActivity;
import com.rongshu.sendmessage.adapter.MessageAdapter;
import com.rongshu.sendmessage.base.BaseActivity;
import com.rongshu.sendmessage.base.BaseFragment;
import com.rongshu.sendmessage.base.MyApplication;
import com.rongshu.sendmessage.bean.AppParameterConfiguration;
import com.rongshu.sendmessage.bean.CarouselFigureList;
import com.rongshu.sendmessage.bean.HeadBean;
import com.rongshu.sendmessage.bean.HealthyRegimenList;
import com.rongshu.sendmessage.util.AnimationUtil;
import com.rongshu.sendmessage.util.ClientPublicParamUtil;
import com.rongshu.sendmessage.util.DialogUtil;
import com.rongshu.sendmessage.util.ObjectUtil;
import com.rongshu.sendmessage.util.StringUtils;
import com.rongshu.sendmessage.util.ToastUtils;
import com.rongshu.sendmessage.util.httpUtil.Constant;
import com.rongshu.sendmessage.util.httpUtil.HYContent;
import com.rongshu.sendmessage.util.httpUtil.IModel;
import com.rongshu.sendmessage.util.itemDecoration.MyItemDecoration;
import com.rongshu.sendmessage.view.banner.BannerViewHolder;
import com.rongshu.sendmessage.view.bottomView.BottomSelectAreaDialog;
import com.rongshu.sendmessage.view.bottomView.BottomSelectCityDialog;
import com.rongshu.sendmessage.view.refresh.ProgressLayout;
import com.rongshu.sendmessage.view.refresh.RefreshListenerAdapter;
import com.rongshu.sendmessage.view.refresh.TwinklingRefreshLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.rongshu.sendmessage.util.httpUtil.HYContent.LA_LO_LOCATION;

public class HomeFragment extends BaseFragment implements MZBannerView.BannerPageClickListener {
    private TextView tv_title;
    private MZBannerView banner_normal;
    private List<CarouselFigureList> list_banner;
    private Context mContext;
    private RecyclerView recycleView;
    private MessageAdapter mAddpayAdapter;
    private List<HealthyRegimenList> mMessageList;
    private String latitude,longitude;
    private String userId;
    private Intent mIntent;
    private SmartRefreshLayout list_refresh;
    private String pullType="";
    private int page=1;
    private View noresult_view;
    private View view_has_new;
    private String callPhone;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mMessageList=new ArrayList<>();
        userId=MyApplication.mSettings.getString(HYContent.UserId,"");
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        list_banner=new ArrayList<>();
        mContext=getContext();
        View rootView=inflater.inflate(R.layout.home_fragment,null);
        initView(rootView);

        return  rootView;
    }
    private void initData() {
        Map<String, String> param = new HashMap<String, String>();
        param.put("userId",userId);
        param.put("longitudeStr",longitude);
        param.put("latitudeStr",latitude);
        param.put("clientPublicParam", ClientPublicParamUtil.getPublicParams(mContext));
        String url = new HYContent().GET_EAND_URL;

        OkGo.<String>post(url).params(param).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                IModel.AjaxResult jr = new IModel.AjaxResult(response.body());
                final int code = jr.getCode();

                if (code>0){
                    HeadBean headBean = JSON.parseObject(JSON.toJSONString(jr.getData()), HeadBean.class);
                    setData(headBean);
                }else{
                    ToastUtils.show(mContext,jr.getMsg());
                    noresult_view.setVisibility(View.VISIBLE);
                    recycleView.setVisibility(View.GONE);
                }
                DialogUtil.hideProgress();
                if (pullType.equals(Constant.PULLTYPE_DOWN)){
                    list_refresh.finishRefresh(true);
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                DialogUtil.hideProgress();
                noresult_view.setVisibility(View.VISIBLE);
                recycleView.setVisibility(View.GONE);
                if (pullType.equals(Constant.PULLTYPE_DOWN)){
                    list_refresh.finishRefresh(false);
                }
            }
        });
    }

    private void setData(HeadBean headBean) {
        AppParameterConfiguration appParameterConfiguration = headBean.getAppParameterConfiguration();
        MyApplication.editor.putString(HYContent.CustomerNumber,appParameterConfiguration.getCustomerNumber());
        MyApplication.editor.putString(HYContent.CustomerWxNum,appParameterConfiguration.getCustomerWxNum());
        MyApplication.editor.putString(HYContent.ServiceQrCode,appParameterConfiguration.getWechatCustomerServiceQrCode());
        MyApplication.editor.putString(HYContent.ServiceHours,appParameterConfiguration.getCustomerServiceHours());
        MyApplication.editor.putString(HYContent.AppStartPageImg,appParameterConfiguration.getAppStartPageImg());
        MyApplication.editor.commit();
       if (headBean.isNewMsgYesNo()){
           view_has_new.setVisibility(View.VISIBLE);
       }else{
           view_has_new.setVisibility(View.GONE);
       }
        list_banner.clear();
        list_banner.addAll(headBean.getCarouselFigureList());
        banner_normal.setPages(list_banner, (MZHolderCreator<BannerViewHolder>) BannerViewHolder::new);
        if (list_banner==null||list_banner.size()<=1){
            banner_normal.setIndicatorRes(R.color.transparent,R.color.transparent);
        }else{
            banner_normal.setIndicatorRes(R.drawable.gray_dian_color,R.drawable.white_dian_color);
        }
        banner_normal.start();
        List<HealthyRegimenList> healthyRegimenList = headBean.getHealthyRegimenList();
        if (healthyRegimenList.size()==0){
            noresult_view.setVisibility(View.VISIBLE);
            recycleView.setVisibility(View.GONE);
        }else{
            recycleView.setVisibility(View.VISIBLE);
            noresult_view.setVisibility(View.GONE);
        }
        boolean isSame=true;
        if (mMessageList.size()==healthyRegimenList.size()){
            for (int i = 0; i < mMessageList.size(); i++) {
                if (!mMessageList.get(i).getId().equals(healthyRegimenList.get(i).getId())){
                    isSame=false;
                }
            }
        }else {
            isSame=false;
        }
        boolean isEdit=MyApplication.mSettings.getBoolean(HYContent.IS_EDIT,false);
        if (isEdit){
            isSame=false;
        }
        if (isSame){
            return;
        }
        mMessageList.clear();
        mMessageList.addAll(healthyRegimenList);
        mAddpayAdapter.setmList(mMessageList);
        mAddpayAdapter.notifyDataSetChanged();
    }


    private void initView(View rootView) {
        tv_title=rootView.findViewById(R.id.tv_title);
        noresult_view=rootView.findViewById(R.id.noresult_view);
        view_has_new=rootView.findViewById(R.id.view_has_new);
        list_refresh=rootView.findViewById(R.id.list_refresh);
        list_refresh.setEnableLoadmore(true);
        list_refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pullType= Constant.PULLTYPE_DOWN;
                page=1;
                initData();

            }
        });
        list_refresh.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                pullType = Constant.PULLTYPE_UP;
                page++;
                refreshData();
            }
        });

        View ll_more = rootView.findViewById(R.id.ll_more);
        ll_more.setOnClickListener(view->{
            mIntent=new Intent(mContext, MoreMessageActivity.class);
            mIntent.putExtra("source","my");
            startActivity(mIntent);
        });
        View ll_weizhi = rootView.findViewById(R.id.ll_weizhi);
        ll_weizhi.setOnClickListener(view->{
            BottomSelectCityDialog dialog=new BottomSelectCityDialog(userId,"location", new BottomSelectCityDialog.IEditAreaClick() {
                @Override
                public void editArearClick(String city, String cityCode) {
                    if (!StringUtils.isEmpty(city)){
                        tv_title.setText(city);
                        MyApplication.editor.putString(HYContent.CITY_NAME,city);
                        MyApplication.editor.putString(HYContent.CITY_CODE,cityCode);
                        MyApplication.editor.commit();
                    }
                }
            });
            dialog.showDialog(mContext);
        });
        View tv_search_1 = rootView.findViewById(R.id.tv_search_1);
        tv_search_1.setOnClickListener(view->{
            gotoSearch();
        });
        View iv_search = rootView.findViewById(R.id.iv_search);
        iv_search.setOnClickListener(view->{
            gotoSearch();
        });
        recycleView=rootView.findViewById(R.id.recycleView);
        initRecycleView();
        banner_normal =rootView.findViewById(R.id.banner_normal);
        banner_normal.setIndicatorRes(R.color.transparent,R.color.transparent);
        banner_normal.setBannerPageClickListener(this);
    }

    private void gotoSearch() {
        mIntent=new Intent(mContext, SearchActivity.class);
        startActivity(mIntent);
    }

    private void refreshData() {
        Map<String, String> param = new HashMap<String, String>();
        param.put("clientPublicParam", ClientPublicParamUtil.getPublicParams(mContext));
        param.put("keyWord", "");
        param.put("page", page+"");
        //
        OkGo.<String>post(new HYContent().GET_FABU_LIST_URL).params(param).tag("GET_FABU_LIST_URL").
                execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        list_refresh.finishLoadmore(true);
                        try {
                            IModel.AjaxResult jr = new IModel.AjaxResult(response.body());
                            final int code = jr.getCode();
                            if (code>0){
                                List<HealthyRegimenList> messageLists = JSON.parseArray(JSON.toJSONString(jr.getJSONArrayData()), HealthyRegimenList.class);
                                if (messageLists.size()==0){
                                    ToastUtils.show(mContext,getResources().getString(R.string.no_more));
                                    return;
                                }

                                mMessageList.addAll(messageLists);
                                mAddpayAdapter.setmList(mMessageList);
                                mAddpayAdapter.notifyDataSetChanged();
                            }else{
                                ToastUtils.show(mContext,jr.getMsg());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        if (pullType.equals(Constant.PULLTYPE_DOWN)) {
                            list_refresh.finishRefresh(false);
                        } else {
                            list_refresh.finishLoadmore(false);
                        }
                    }
                });
    }

    private void initRecycleView() {
        recycleView.setHasFixedSize(true);//设置固定大小
        recycleView.setItemAnimator(new DefaultItemAnimator());//设置默认动画
        recycleView.addItemDecoration(new MyItemDecoration());
        recycleView.addItemDecoration(new MyItemDecoration(0, 0));
        GridLayoutManager mLayoutManage = new GridLayoutManager(mContext, 1);
        recycleView.setLayoutManager(mLayoutManage);
        recycleView.setLayoutAnimation(AnimationUtil.getAnimationController());

        mAddpayAdapter = new MessageAdapter(mContext,"home", R.layout.message_item, mMessageList);
        recycleView.setAdapter(mAddpayAdapter);
        //recycleview的点击事件
        mAddpayAdapter.setOnItemClickListener((view, position) -> {
            if (view.getId()==R.id.re_zhankai){
                //展开收起的
                boolean isshow = !mMessageList.get(position).isShow();
                mMessageList.get(position).setShow(isshow);
                mAddpayAdapter.setmList(mMessageList);
                mAddpayAdapter.notifyItemChanged(position);

            } else if (view.getId()==R.id.ll_bianji){
                //去编辑

            }else if (view.getId()==R.id.iv_phone){
                callPhone=mMessageList.get(position).getContactPhone();
                if (ObjectUtil.checkReadPermission((BaseActivity)mContext, Manifest.permission.CALL_PHONE, ObjectUtil.REQUEST_CALL_PERMISSION)) {
                    goCall();
                }
            }else{
                Intent intent=new Intent(mContext, MessageDetailActivity.class);
                String id = mMessageList.get(position).getId();
                intent.putExtra("articleId",id);
                startActivity(intent);
            }
        });
    }
    /**
     * 检查权限后的回调
     *
     * @param requestCode  请求码
     * @param permissions  权限
     * @param grantResults 结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case ObjectUtil.REQUEST_CALL_PERMISSION: //拨打电话
                if (permissions.length != 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {//失败
                    Toast.makeText(mContext, "请允许拨号权限后再试", Toast.LENGTH_SHORT).show();
                } else {//成功
                    goCall();
                }
                break;
        }
    }
    private void goCall() {
        DialogUtil.showConfirmDialog(mContext, "提示", "您确定给" + callPhone + "打电话吗?", new DialogUtil.OnDialogListener<Void>() {
            @Override
            public void onPositiveButtonClick(Void aVoid) {
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + callPhone));//直接拨打电话
                if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }
                mContext.startActivity(intent);
            }

            @Override
            public void onNegativeButtonClick(Void aVoid) {

            }
        });
    }

    public void setLocationCity(String cityTitle) {
        String cityName = MyApplication.mSettings.getString(HYContent.CITY_NAME, "");
        MyApplication.editor.putString(HYContent.CITY_LOCATION_NAME,cityTitle);
        if (StringUtils.isEmpty(cityName)){
            MyApplication.editor.putString(HYContent.CITY_NAME,cityTitle);
            tv_title.setText(cityTitle);
        }else{
            tv_title.setText(cityName);
        }
        MyApplication.editor.commit();
        String laloLocation = MyApplication.mSettings.getString(LA_LO_LOCATION, "");
        if (!StringUtils.isEmpty(laloLocation)){
            String[] split = laloLocation.split(",");
            if (split.length>=2){
                latitude=split[0];
                longitude=split[1];
            }
        }

        DialogUtil.showProgress(mContext);
        initData();
    }
    @Override
    public void onPageClick(View view, int position) {
        if (list_banner != null && list_banner.size() > 0) {
            CarouselFigureList cfdList = list_banner.get(position);
//            ToastUtils.show(mContext, "点击了第:"+position);
            String id = cfdList.getId();
        } else {
//            AppToast.show(mContext, "无数据条目，暂不支持点击");
        }
    }

    @Override
    public void upData(int position) {
        super.upData(position);
        if (position==0)
            initData();
    }


}
